package com.xiaoyuanxing.demo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoyuanxing.demo.entity.Order;
import com.xiaoyuanxing.demo.mapper.OrderMapper;
import com.xiaoyuanxing.demo.mapper.OrderTakerMapper;
import com.xiaoyuanxing.demo.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/*
 **@author LuoShengYing
 **@date 2021/5/23
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderTakerMapper orderTakerMapper;

    @Override
    public Page<Order> getOrdersByIDs(List<Integer> orderIDs, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return orderMapper.selectListByOrderIDs(orderIDs);
    }

    @Override
    public Order getOrderByID(int ID) {
        return orderMapper.selectByOrderID(ID);
    }

    @Override
    public Page<Order> getOrderIDsByCreatorID(long creatorID, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return orderMapper.selectListByCreatorID(creatorID);
    }

    @Override
    public Page<Order> getOrderIDsByTakerID(long takerID, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return orderMapper.selectListByOrderIDs(orderTakerMapper.selectListByTakerID(takerID));
    }

    @Override
    public Page<Order> getOrdersByStatus(int status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return orderMapper.selectListByStatus(status);
    }

    @Override
    public void createNewOrder(Order order) {
        orderMapper.insertOrder(order);
    }

    @Override
    public boolean takeOrder(int orderID, long takerID) {
        return orderMapper.updateStatus(orderID,0) && orderTakerMapper.insertOrderTaker(orderID, takerID);
    }


    @Override
    public boolean updateStatusAsFinish(int orderID) {
        orderMapper.updateCompletedTime(orderID, new Timestamp(System.currentTimeMillis()) );
        return orderMapper.updateStatus(orderID, 1);
    }

    @Override
    public boolean deleteOrder(int orderID) {
        //  获取该订单的状态，如果状态不为-1，则无法删除，并返回false
        Order order = orderMapper.selectByOrderID(orderID);
        if (order.getStatus() != -1){
            return false;
        }
        return  orderMapper.deleteByOrderID(orderID);
    }
}
